<!--
@ 作者: 阿拉丁矿工 黄传鸿 <hchhyzc@foxmail.com>
-->
<template>
  <div class="right_project">
    <!-- 第1行工具 -->
    <div class="h_flex_row_around h_margin_5">
      <!-- 获取工程列表 -->
      <NTooltip class="bottom_icon" placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="0 0 1024 1024"
            v-html="onGetDataManagerIcon('fileGetListIcon')" @click="onProjectGetList()"></svg>
        </template>
        <span>获取工程列表</span>
      </NTooltip>
      <!-- 新建工程 -->
      <NTooltip class="bottom_icon" placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="0 0 1024 1024"
            v-html="onGetDataManagerIcon('fileNewIcon')" @click.stop="onProjectNew()"></svg>
        </template>
        <span>新建工程</span>
      </NTooltip>
      <!-- 保存工程 onProjectSave-->
      <NTooltip class="bottom_icon" placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="0 0 1024 1024"
            v-html="onGetDataManagerIcon('fileSaveIcon')" @click="onProjectSave()"></svg>
        </template>
        <span>保存工程</span>
      </NTooltip>
      <!-- 工程备份 -->
      <NTooltip class="bottom_icon" placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="0 0 1024 1024"
            v-html="onGetDataManagerIcon('fileSaveAsIcon')" @click="onProjectSaveAs()"></svg>
        </template>
        <span>工程备份</span>
      </NTooltip>
      <!-- 导出工程 -->
      <NTooltip placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="0 0 1024 1024"
            v-html="onGetDataManagerIcon('fileLeadingOutIcon')" @click="onProjectLeadOutJSON()"></svg>
        </template>
        <span>导出工程</span>
      </NTooltip>
      <!-- 导入工程 -->
      <NTooltip placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="0 0 1024 1024"
            v-html="onGetDataManagerIcon('fileLeadingInIcon')" @click="onOpenFileDialog()"></svg>
        </template>
        <span>导入工程</span>
      </NTooltip>
    </div>
    <!-- 第2行工具 -->
    <NDivider />
    <div class="h_flex_row_around h_margin_5">
      <!-- 开启服务 -->
      <NTooltip class="bottom_icon" placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="0 0 1024 1024"
            v-html="onGetDataManagerIcon('startIcon')" @click="onStartServer()"></svg>
        </template>
        <span>开启服务</span>
      </NTooltip>
      <!-- 关闭服务 -->
      <NTooltip class="bottom_icon" placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="0 0 1024 1024"
            v-html="onGetDataManagerIcon('stopIcon')" @click="onStopServer()"></svg>
        </template>
        <span>关闭服务</span>
      </NTooltip>
      <!-- 初始化数据库 -->
      <NTooltip class="bottom_icon" placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="0 0 1024 1024"
            v-html="onGetDataManagerIcon('initDBIcon')" @click="onInitDatabase()"></svg>
        </template>
        <span>初始化数据库</span>
      </NTooltip>
      <!-- 开启驱动扫描 -->
      <NTooltip class="bottom_icon" placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="0 0 1024 1024"
            v-html="onGetDataManagerIcon('scanIcon')" @click="onStartDriveScan()"></svg>
        </template>
        <span>开启驱动扫描</span>
      </NTooltip>
      <!-- 预览视图 -->
      <NTooltip class="bottom_icon" placement="bottom" trigger="hover">
        <template #trigger>
          <svg class="h_svg_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            version="1.1" :width="IconSize" :height="IconSize" viewBox="-10 -10 1024 1024"
            v-html="onGetDataManagerIcon('dataPreviewIcon')" @click="onWorkView()"></svg>
        </template>
        <span>预览视图</span>
      </NTooltip>
    </div>


    <NDivider />
    <!-- 工程名称 -->
    <div class="h_info">
      <text class="h_info_lable">工程名称</text>
      <NInput class="h_info_val" type="textarea" v-model:value="projectStore.label" />
    </div>
    <!-- 保存时间 -->
    <div class="h_info">
      <text class="h_info_lable">保存时间</text>
      <text class="h_info_val">{{ projectStore.calendar }}</text>
    </div>
    <!-- id -->
    <div class="h_info">
      <text class="h_info_lable">id:</text>
      <text class="h_info_val">{{ projectStore.key }}</text>
    </div>
    <!-- id -->
    <div class="h_info">
      <text class="h_info_lable">当前页面:</text>
      <text class="h_info_val">{{
        projectStore.pages[projectStore.pageIndex].label
      }}</text>
    </div>
    <NDivider />
    <!-- 分割线 -->
    <div style="width: 10px"></div>
    <!-- 页面表 -->
    <div class="right_project_page">
      <n-data-table size="small" :max-height="300" :columns="Columns" :pagination="Pagination" :data="Store.Pages" />
    </div>
    <!-- 文件导入 -->
    <input type="file" style="display: none" ref="fileRef" @change="onLeadingIn" />
  </div>
</template>

<script setup lang="ts">
/* ================================================================================================ */
// 🍀引入
/* ================================================================================================ */
import { NButton } from "naive-ui";
import type { DataTableColumns } from "naive-ui";
import { useRouter } from "vue-router";
import axios from "axios";
import { useMessage } from 'naive-ui';
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 图元端函数引入
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
import {
  onGetDataManagerIcon,
  saveProject, //保存工程
  saveProjectToCanvas, //转储-从_工程存储_到_画布存储
  onProjectNew, // 新建工程
  onProjectGetList, // 获取工程列表
  onProjectSave, // 保存工程
  onProjectSaveAs, // 备份工程
  onProjectLeadOutJSON, //
  onActionDownNavigation,
  onRecordLog,//日志处理器
  onSetCurrentPage,
  onDeletePage,
} from "@/functions";

/**🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾*/
// 🐸 引入存储
/**🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾🌾*/
import { useMenuStore } from "@/store/menuStore"; // 菜单
import { useCanvasStore } from "@/store/canvasStore"; // 画布
import { useProjectStore } from "@/store/projectStore"; // 工程
import { storeToRefs } from "pinia";

/**👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾👨‍🌾*/
// 🐸 使用存储
/**👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾👩‍🌾*/
const menuStore = useMenuStore(); // 菜单
const projectStore = useProjectStore(); // 工程
const canvasStore = useCanvasStore(); // 画布
const message = useMessage()// 消息
const router = useRouter();
/* ================================================================================================ */
//                                 ★变量
/* ================================================================================================ */
// const { getDataManager }storeToRefs(menuStore);
/** 存储 */
let Store = reactive({
  /** 工程名称 */
  ProjectName: computed(() => projectStore.pages[projectStore.pageIndex].pageName),
  /** 页面 */
  Pages: computed(() => projectStore.pages),
  /** 页面键 */
  pageKey: computed(() => projectStore.pages[projectStore.pageIndex].pageKey),
});
/** 图标尺寸 */
const IconSize = 30;
/** 列标 */
let Columns = [
  {
    title: "页面名称",
    key: "label",
    width: 80,
  },
  {
    title: "控制",
    key: "ctrls",
    width: 160,
    render(Row: RowData) {
      if (Row.key !== Store.pageKey) {
        return [
          h(
            NButton,
            {
              style: { marginLeft: "6px" },
              size: "tiny",
              type: "info",
              onClick: () => onSetCurrentPage(Row.key),
            },
            { default: () => "置当前" }
          ),
          h(
            NButton,
            {
              style: { marginLeft: "6px" },
              size: "tiny",
              type: "error",
              onClick: () => onDeletePage(Row.key),
            },
            { default: () => "删除" }
          ),
        ];
      } else {
        return [
          h(
            "div",
            {
              style: { marginLeft: "6px" },
              size: "small",
            },
            { default: () => "当前页面" }
          ),
        ];
      }
    },
  },
];
/** 分页 */
let Pagination: {
  pageSize: 1000;
};
/** 行数据定义 */
type RowData = {
  table: string; // 名称
  key: string; // 键或Id
};
/** 文件参数 */
let fileRef = ref();

/* ================================================================================================ */
//                                函数 ★
/* ================================================================================================ */

/** 打开文件对话框 */
const onOpenFileDialog = () => {
  // console.log("打开文件对话框");
  // console.log(fileRef.value);
  fileRef.value.dispatchEvent(new MouseEvent("click"));
};

/**  导入 */
const onLeadingIn = async () => {
  // console.log("图元数据-导入");
  // console.log(fileRef)
  // console.log(fileRef.value.files[0])
  // 读取文件
  const file = fileRef.value.files[0];
  const reader = new FileReader();
  reader.readAsText(file);
  reader.onload = () => {
    // 解析JSON
    const jsonData = JSON.parse(reader.result);
    // console.log(jsonData);
    if (jsonData.type === "project") {
      saveProject(jsonData.project); // 保存工程

      /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
      // 🐸 转储-工程存储_到_画布存储
      /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
      saveProjectToCanvas(); // 转储-从_工程存储_到_画布存储
      setTimeout(() => {
        onActionDownNavigation("DownProject"); // 激活下框导航-工程
      }, 100);
      /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
      // 🐸 提示 记录到日志
      /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
      onRecordLog(`成功导入工程-${jsonData.project.key}`);
      message.success("成功导入工程");
    } else {
      onRecordLog("文件错误");
      message.error("文件错误");
    }
  };
};

/** 开启服务 */
const onStartServer = () => {
  // console.log("开启服务");
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  // 🐸 发送
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  axios({
    url: `/api/HCIOT?query=startServer`,
    method: 'get',
  })
    .then((response: any) => {
      if (response.status === 200) {
        onRecordLog(`开启服务成功`)
        message.success("开启服务成功");
      } else {
        onRecordLog(`开启服务失败`)
        message.error("开启服务失败");
      }
    })
    .catch(() => {
      onRecordLog(`开启服务失败`)
      message.error("开启服务失败");
    })
}

/** 停止数据服务 */
const onStopServer = () => {
  // console.log("停止数据服务");
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  // 🐸 发送
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  axios({
    url: `/api/HCIOT?query=stopServer`,
    method: 'get',
  })
    .then((response: any) => {
      if (response.status === 200) {
        onRecordLog(`停止数据服务成功`);
        message.success("停止数据服务成功");
      } else {
        onRecordLog(`停止数据服务失败`);
        message.error("停止数据服务失败");
      }
    })
    .catch(() => {
      onRecordLog(`停止数据服务失败`);
      message.error("停止数据服务失败");
    })
};

/** 初始化数据库 */
const onInitDatabase = () => {
  // console.log("初始化数据服务");
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  // 🐸 发送
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  axios({
    url: `/api/HCIOT?query=initDatabase`,
    method: 'get',
  })
    .then((response: any) => {
      if (response.status === 200) {
        onRecordLog(`初始化数据库成功`);
        message.success("初始化数据库成功");
      } else {
        onRecordLog(`初始化数据库失败`);
        message.error("初始化数据库失败");
      }
    })
    .catch(() => {
      onRecordLog(`初始化数据库失败`);
      message.error("初始化数据库失败");
    })
};

/** 开启驱动扫描 */
const onStartDriveScan = () => {
  // console.log("开启驱动扫描");
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  // 🐸 发送
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  axios({
    url: `/api/HCIOT?query=startDraveScan`,
    method: 'get',
  })
    .then((response: any) => {
      if (response.status === 200) {
        onRecordLog(`开启驱动扫描成功`);
        message.success("开启驱动扫描成功");
      } else {
        onRecordLog(`开启驱动扫描失败`);
        message.error("开启驱动扫描失败");
      }
    })
    .catch(() => {
      onRecordLog(`开启驱动扫描失败`);
      message.error("开启驱动扫描失败");
    })
};

/** 工作视图 */
const onWorkView = () => {
  // console.log("工作视图")
  /** 路由 */
  const url = router.resolve({
    path: "/home",
  });
  // 打开新窗口
  window.open(url.href);
};

/* ================================================================================================ */
//                               ★监听
/* ================================================================================================ */
//监听-工程名称
watch(
  () => Store.ProjectName,
  () => {
    // console.log("监听-工程名称");
    onProjectSave(); // 保存工程
  }
);
</script>

<style lang="scss" scoped>
/* 引入共用css */
@import "@/assets/h.scss";

.right_project {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  overflow: hidden;
}

.right_project_page {
  height: 300px;
}

/* 参数 */
.h_info {
  padding: 5px;
  width: 100%;
  user-select: none;
  display: flex;
  flex-direction: row;
  justify-content: start;
  align-items: center;
  font-size: 12px;
}

/* 参数标题 */
.h_info_lable {
  padding-left: 3px;
  width: 80px;
}

/* 参数变量 */
.h_info_val {
  width: 100%;
  margin-right: 16px;
}
</style>
